package com.mgq.netty.c9;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.nio.charset.StandardCharsets;

/**
 * @author MaGuangQi
 * @description: 使用netty提供的行解码器
 * {@link LineBasedFrameDecoder},自定义分隔符{@link DelimiterBasedFrameDecoder}
 * 缺点:需要一个字节一个字节去解析,耗费性能.不常用
 * @date 2021-12-06 15:14
 **/
public class ThirdSolution {
    public static void main(String[] args) {
        // 模拟服务器
        // 使用EmbeddedChannel测试handler
        EmbeddedChannel channel = new EmbeddedChannel(
                //设置最大长度,超过抛出 TooLongFrameException
                new LineBasedFrameDecoder(64),
                new LoggingHandler(LogLevel.DEBUG)
        );

        // 模拟客户端，写入数据
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
        buffer.writeBytes("hello\nworld!\n".getBytes(StandardCharsets.UTF_8));
        channel.writeInbound(buffer);
        /*Random random = new Random();
        for (int i = 0; i < 10; i++) {
            String content = String.valueOf(random.nextInt()) + "\n";
            buffer.writeBytes(content.getBytes(StandardCharsets.UTF_8));
            channel.writeInbound(buffer);
        }*/
    }

}
